<?php defined('SYSPATH') or die('No direct script access.');

/**
 * Manager for Envy Module
 * The manager looks for configured placeholders defined in config/eny/php. From here, it looks for each template file defined
 * in this file, and merges any placeholders with the defined values for the specified environment
 *
 * @package    Envy Module 
 * @author     Howie Weiner
 * @license    http://creativecommons.org/licenses/BSD/
 */

class Envy_Manager
{
	private $env;
	private $placeholders;

    public function __construct($env) {

		$this->env = $env;
		$this->placeholders = Kohana::config('envy.'.$env);
		
		if(empty($this->placeholders))
		{
			die ("There is nothing configured to setup for the ".$env." environment\n");
		}
    }

	/**
	 * Updates the placeholders in the template files
	 * @return void
	 */
	public function update_files()
	{
		// find which files need updating
		$files = Kohana::config('envy.files');

		foreach($files as $file)
		{
			echo "Preparing to update file ".$file."...\n";
			$this->merge($file);
		}
	}

	
	private function merge($path)
	{	
		$path = strtolower( trim($path) );
		
		// TODO:: can't use Kohana::find_file as it returns an Array for config files. We do need the cascading file search
		// to allow this to work with modules an sub directories

		// find template file containing placeholders. We only want the filename, not the path
		$filename = explode(DIRECTORY_SEPARATOR, $path);
		$filename = $filename[sizeof($filename)-1];

		$template_path = APPPATH.'envy'.DIRECTORY_SEPARATOR.'templates'.DIRECTORY_SEPARATOR.$filename.EXT;
		
		// Disable error reporting while opening the file
		$ER = error_reporting(0);

		$file = file_get_contents($template_path,"r");

		// Restore error reporting
		error_reporting($ER);

		if(false == $file)
		{
			echo "Could not find template file ".$template_path." - skipping...\n";
			return;
		}
        
		// find file to update. If filename is index, look in DOCROOT, otherwise APPPATH
		
		$file_path = ('index' === $path) ? DOCROOT.$path.".php" : APPPATH.$path.EXT;

		// merge placeholders in the template file
		foreach($this->placeholders as $k => $v)
		{
			$placeholder = "{".$k."}";
			//echo "Replacing placeholder: ".$placeholder ."\n";
			
			$file = str_replace($placeholder, $v, $file);
		}

		// save mrged file
		file_put_contents($file_path, $file);
		
		echo "Succesfully updated file ".$path."\n\n";
	}
} // End Envy_Manager